package org.simple.webserver.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.util.LinkedMultiValueMap;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author HaiLang
 * @date 2021/8/19 6:34 下午
 */
@Slf4j
public class MyWebServer implements WebServer {

    private final AtomicBoolean started = new AtomicBoolean(false);

    private final HttpHandler httpHandler;

    private final Thread main;

    public MyWebServer(HttpHandler httpHandler) {
        this.httpHandler = httpHandler;
        this.main = new Thread(() -> {
            try {
                ServerSocket serverSocket = new ServerSocket();
                serverSocket.bind(new InetSocketAddress(8888));
                while (started.get()) {
                    //收到客户端的请求
                    Socket socket = serverSocket.accept();

                    //输入流用于接收客户端传输过来的数据
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                        //按照HTTP协议，请求头和请求体之间为一空行分隔
                        if ("".equals(line)) {
                            break;
                        }
                    }
                    //http协议解析成NginxServerHttpRequest
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.setContentLength(18);
                    headers.setHost(new InetSocketAddress(8080));
                    headers.setAccept(Collections.singletonList(MediaType.ALL));
                    headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
                    MyServerHttpRequest request = new MyServerHttpRequest(
                            URI.create("http://localhost:8888/test/hello2?param=aaa&param1=bbb"),
                            "", headers, new LinkedMultiValueMap<>(),
                            "GET", Collections.singletonList("{\"hello\": \"world\"}"));
                    MyServerHttpResponse response = new MyServerHttpResponse(socket);
                    httpHandler.handle(request, response)
                            //真正触发调用
                            .subscribe();
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    public void start() throws WebServerException {
        started.compareAndSet(false, true);
        main.start();
        System.out.println("nginx webserver started !");
    }

    @Override
    public void stop() throws WebServerException {
        started.compareAndSet(true, false);
    }

    @Override
    public int getPort() {
        //在nginx.conf的配置中
        return 8888;
    }

}